function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function showAlert(alertClass, alertText){
    $('<div/>', {
        'class': alertClass,
        'text': alertText
    }).hide()
    .append('<button type="button" class="close" data-dismiss="alert">×</button>')
    .appendTo('header.page-header').slideDown();
}
function getUsers(){
    var list = [];
    $('#orders tbody td:first-child').each(function(){
        var text = $(this).text().trim();
        if(list.indexOf(text) == -1) list.push(text);
    });
    return list;
}
$.ajaxSetup({
    crossDomain: false,
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

$.fn.YouTubePopup.defaults.hideTitleBar = true;
$.fn.YouTubePopup.defaults.fullscreen = 0;
$.fn.YouTubePopup.defaults.useYouTubeTitle = false;
$.fn.YouTubePopup.defaults.clickOutsideClose = true;
$.fn.YouTubePopup.defaults.showinfo = 0;

$(function(){
    $('#login-a').attr('href', '#login');
    $('#signup-a').attr('href', '#signup');
    $('label').addClass('control-label');
    $('tbody i').tooltip({placement: 'right'});
    $('tbody a.btn').attr('href', '#login');
    $('tbody a.order').click(function(e){
        e.preventDefault();
        var $button = $(this);
        var alertClass = 'alert';
        var alertText = '';
        if($button.hasClass('disabled')){
            alertClass += ' alert-error';
            alertText = 'Pozycja "' + $button.parent().parent().children('td:first').text() + '" jest niedostępna';
            showAlert(alertClass, alertText);
         } else {
            $button.button('loading');
            var title = $button.parent().parent().children('td:first').text();
            $.ajax({
                url: '/order/',
                type: 'POST',
                data: {value: $button.data('value')},
                success: function(data){
                    alertText = 'Zamówiono pozycję "' + title + '"';
                    $button.button('reset').text('Gotowe').addClass('btn-success').removeClass('btn-primary btn-danger');
                    showAlert(alertClass, alertText);
                },
                error: function(xhr, ajaxOptions, thrownError){
                    alertText = xhr.responseText;
                    if(alertText == 'already ordered'){
                        alertText = 'Pozycja "' + title + '" była juz zamówiona';
                    } else if(alertText == 'no item'){
                        alertText = 'Nie znaleziono pozycji "' + title + '"';
                    } else if ('login first') {
                        alertText = 'By złożyć zamówienie zaloguj się lub zarejestruj';
                    } else {
                        alertText = "Wystąpił błąd - spróbuj ponownie później";
                    }
                    alertClass += ' alert-error';
                    $button.button('reset').text('Błąd').removeClass('btn-success').addClass('btn-danger');
                    showAlert(alertClass, alertText);
                }
            });

        }
    });
    $('tbody button').click(function(){
        var $this = $(this);
        $.ajax({
            url: '/changeorder/',
            type: 'POST',
            data: {
                value: $this.parent().data('value'),
                type: $this.data('type')
            },
            success: function(){
                location.reload();
            },
            async: false
        });
    });
    $('ul.dropdown-menu').click(function(e){
        var $icon_class = $(e.target).children('i').first().attr('class');
        $('#search').attr('class', $icon_class);
        var type = {
            "icon-film": "dvd",
            "icon-book": "paper",
            "icon-search": "all",
            "icon-music": "vinyl",
            "icon-headphones": "cd",
            "icon-download-alt": "digital"
        };
        $("#type").val(type[$icon_class]);
    });
    $('#login-form, #signup-form').submit(function(e){
        e.preventDefault();
        $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            type: 'POST',
            data: $form.serializeArray(),
            success: function(data){
                location.reload();
            },
            error: function(xhr, ajaxOptions, thrownError){
                $form.siblings('div.alert').remove();
                $form.parent().prepend(xhr.responseText);
            }
        });
    });
    $('a.yt').each(function(){
        $yt = $(this);
        var yt_id = $yt.attr('rel').split('?v=')[1].split('&')[0];
        $yt.YouTubePopup({
           'youtubeId': yt_id
       });
    });
    $('#filter').typeahead({source: getUsers});
    var $filterForm = $('#filter_form');
    $filterForm.submit(function(e){
        e.preventDefault();
        var $this = $(this);
        var search = "";
        search = $this.serializeArray()[0]['value'];
        if (search==""){
            $('#orders tbody').fadeIn();
        } else {
            $('#orders tbody').each(function(){
                var found = false;
                var $this = $(this);
                $this.find('tr td').each(function(){
                    if($this.text().indexOf(search) > -1)
                        found = true;
                });
                if(found){
                    $this.fadeIn();
                } else {
                    $this.fadeOut();
                }
            });
        }
    });
    $filterForm.on('reset', function(){
        $('#orders tbody').fadeIn();
    });
});

document.addEventListener("DOMNodeInserted", function(event) {
    var $element = $(event.target)
    var $parent = $element.parent();
    if ($parent.is('span') && $element.is('img')){
        $parent.empty().append($parent.siblings('a'));
    }
    else if ($element.is('iframe')){
        $parent = $parent.parent();
        var style = $parent.attr('style');
        style = style.replace(/background-color: rgb\(\d{3}, \d{3}, \d{3}\)/g, 'background-color: rgb(255, 255, 255)');
        $parent.attr('style', style);

    }
});
